const userSer = require('../../service/user/userSer')
const jwt = require("../../config/jwt");
const saveAudio = require('../../utils/saveAudio')
const sqlCondition = require('../../utils/sqlCondition')
const saveImg = require("../../utils/saveImg");
const passwordCon = require('../../utils/bcryptPassword')

class UserCon {
    // 检查用户token是否过期
    async examineToken(ctx) {
        try {
            const token = ctx.request.header.authorization.split('Bearer ')[1];
            const payload = await jwt.verify(token);
            const date = new Date().getTime();
            if ((payload.exp * 1000) < date) {
                ctx.body = {
                    code: 40002,
                    message: '令牌已过期,请重新登录'
                };
                ctx.log4js.info('路径:' + ctx.url + '/信息:令牌已过期,请重新登录/参数:' + JSON.stringify(ctx.request.body))
            } else {
                ctx.body = {
                    code: '200',
                };
            }
        } catch (error) {
            if (error.message === 'jwt expired') {
                ctx.body = {
                    code: 40002,
                    message: '令牌已过期,请重新登录'
                };
                ctx.log4js.info('路径:' + ctx.url + '/信息:令牌已过期,请重新登录/参数:' + JSON.stringify(ctx.request.body))
            }
        }
    }

    //注册
    async addUser(ctx) {
        try {
            const userData = ctx.request.body
            const searchData = await userSer.getUserOne({userNumber: userData.userNumber})
            if (searchData.length) {
                ctx.body = {
                    code: '201',
                    message: '该账号已存在'
                }
            } else {
                userData.password = passwordCon.encryption(userData.password)
                const data = await userSer.addUser(userData)
                if (data.dataValues) {
                    ctx.body = {
                        code: '200'
                    }
                } else {
                    ctx.body = {
                        code: '999'
                    }
                }

            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }
    }

    // 查询用户
    async getUserOne(ctx) {
        const {userNumber} = ctx.request.body
        try {
            const data = await userSer.getUserOne({userNumber: userNumber})
            ctx.body = {
                code: '200',
                data: data
            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }
    }

    //编辑用户
    async editUser(ctx) {
        try {
            const data = await userSer.editUser(ctx.request.body)
            if (data[0] === 1) {
                ctx.body = {
                    code: '200',
                    data: data
                }
            } else {
                ctx.body = {
                    code: '999',
                }
            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }

    }

    // 找回密码
    async retrievePassword(ctx) {
        try {
            const userData = ctx.request.body
            const user = await userSer.getUserOne({userNumber: userData.userNumber})
            if (user.length) {
                if (user[0].dataValues.userEmail === userData.userEmail && user[0].dataValues.userPhone === userData.userPhone) {
                    const editData = {
                        userNumber: userData.userNumber,
                        password: passwordCon.encryption(userData.password)
                    }
                    const setUserData = await userSer.editUser(editData)
                    if (setUserData[0] === 1) {
                        ctx.body = {
                            code: '200',
                            message: '修改成功'
                        }
                    } else {
                        ctx.body = {
                            code: '999',
                            message: '修改失败，请联系管理员'
                        }
                    }
                } else {
                    ctx.body = {
                        code: '999',
                        message: '邮箱或手机号码输入错误'
                    }
                }
            } else {
                ctx.response.body = {
                    code: '999',
                    message: '用户不存在'
                }
            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }

    }

    //上传背景音乐
    async uploadAudio(ctx) {
        try {
            //上传的背景音乐
            const audioFile = ctx.request.files.file
            if (!audioFile) {
                ctx.status = 400
                ctx.body = {
                    code: '999',
                    data: '上传文件不能为空'
                }
            }
            //保存音乐获取路径
            const isok = await saveAudio(audioFile)
            if (isok) {
                // 获取当前登录账号
                const userNumber = await jwt.verify(ctx.request.header.authorization.split('Bearer ')[1]).userNumber
                const editProps = {user_background_music: isok}
                const data = await userSer.editUserUrl(editProps, userNumber)
                if (data[0] === 1) {
                    ctx.body = {
                        code: '200',
                        data: ''
                    }
                }
            }

        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }

    }


    // 查询用户列表
    async getUserList(ctx) {
        const req = sqlCondition(ctx.request.body)
        try {
            const data = await userSer.getUserLIst(req)
            ctx.body = {
                code: '200',
                data: data
            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }
    }

    // 拉黑用户
    async blacklistUser(ctx) {
        const userId = ctx.request.body.id
        const type = ctx.request.body.type
        const userData = {user_blacklist: type}
        try {
            const data = await userSer.editUserId(userData, userId)
            if (data[0] === 1) {
                ctx.body = {
                    code: '200'
                }
            } else {
                ctx.body = {
                    code: '999'
                }
            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }
    }

    //用户上传头像
    async uploadAvatar(ctx) {
        try {
            const imgFile = ctx.request.files.file
            // 保存图片
            let ImgUrl
            try {
                ImgUrl = saveImg(imgFile)
            } catch (e) {
                ctx.app.emit('error', e.toString(), ctx)
            }
            ctx.body = {
                code: '200',
                url: ImgUrl,
            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }
    }

}


module.exports = new UserCon()
